package org.nicocube.airain.app.server;

import org.nicocube.airain.app.client.PlayerRegistrationService;
import org.nicocube.airain.app.client.ui.PlayerForm;
import org.nicocube.airain.domain.client.dao.NoPlayerException;
import org.nicocube.airain.domain.client.exception.DomainException;
import org.nicocube.airain.domain.server.dao.DomainDAO;
import org.nicocube.airain.domain.server.storable.Player;
import org.nicocube.airain.domain.server.storable.PlayerDAO;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class PlayerRegistrationServiceImpl extends RemoteServiceServlet	implements PlayerRegistrationService {

	private static final long serialVersionUID = 1L;
	
	private PlayerDAO playerDAO;

	public PlayerRegistrationServiceImpl() {
		playerDAO = DomainDAO.getDao(PlayerDAO.class);
	}
	
	@Override
	public void save(PlayerForm form) throws DomainException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		Player player;
		try {
			player = playerDAO.getByUser(user);
		} catch (NoPlayerException e) {
			player = new Player(user);
		}
		
		player.setEmail(form.getEmail());
		player.setFirstName(form.getFirstName());
		player.setLastName(form.getLastName());
		player.setDateOfBirth(form.getDateOfBirth());
		player.setGender(form.getGender());
		player.setCountry(form.getCountry());
		
		
		playerDAO.save(player);
		
	}

}
